package lessons.no7;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * Serializable 系列化
 */
public class N7_6_1 {
    
    public static void main(String[] args)throws Exception {
        //writeSerializableObject();
        readSerializableObject();
    }

    // Serializable：把对象序列化
    public static void writeSerializableObject() throws Exception
    {
        Man man = new Man("张三", "123456");
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("man.txt"));
        objectOutputStream.writeObject(man);
        objectOutputStream.close();
    }

    // Serializable：把对象反序列化
    public static void readSerializableObject() throws Exception
    {
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("man.txt"));
        Man man = (Man) objectInputStream.readObject();
        objectInputStream.close();
        System.out.println("反序列化对象: " +man);
    }
}

/**
 * 用于系列化
 */
class Man implements Serializable {
    private static final long serialVersionUID = 1L;

    private String username;
    private String password;

    public Man(String username, String password) {
        this.username = username;
        this.password = password;
    }

    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return ""+username+" : "+password;
    }
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
